"""反爬机制处理模块"""

import time
import random
from typing import Dict, List
from fake_useragent import UserAgent
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service


class AntiCrawlerHandler:
    """反爬机制处理器"""
    
    def __init__(self):
        self.ua = UserAgent()
        self.request_count = 0
        self.last_request_time = 0
        
    def get_random_headers(self) -> Dict[str, str]:
        """获取随机请求头"""
        return {
            'User-Agent': self.ua.random,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Cache-Control': 'max-age=0',
            'Sec-Fetch-Dest': 'document',
            'Sec-Fetch-Mode': 'navigate',
            'Sec-Fetch-Site': 'none',
            'Sec-Fetch-User': '?1'
        }
    
    def random_delay(self, min_delay: float = 1.0, max_delay: float = 3.0) -> None:
        """随机延时"""
        delay = random.uniform(min_delay, max_delay)
        time.sleep(delay)
    
    def get_random_delay(self, min_delay: float = 1.0, max_delay: float = 3.0) -> float:
        """获取随机延时时间"""
        return random.uniform(min_delay, max_delay)
    
    def adaptive_delay(self) -> None:
        """自适应延时，根据请求频率调整"""
        current_time = time.time()
        time_diff = current_time - self.last_request_time
        
        # 如果请求过于频繁，增加延时
        if time_diff < 2.0:
            self.random_delay(2.0, 5.0)
        else:
            self.random_delay(1.0, 2.0)
            
        self.last_request_time = current_time
        self.request_count += 1
    
    def create_driver(self, headless: bool = True) -> webdriver.Chrome:
        """创建Chrome驱动（使用Chromium）"""
        options = Options()
        
        # 指定Chromium二进制文件路径
        options.binary_location = '/usr/bin/chromium'
        
        if headless:
            options.add_argument('--headless')
        
        # 反检测设置
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--disable-blink-features=AutomationControlled')
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        
        # 设置用户代理
        options.add_argument(f'--user-agent={self.ua.random}')
        
        # 设置窗口大小
        options.add_argument('--window-size=1920,1080')
        
        # 禁用图片加载以提高速度
        prefs = {
            "profile.managed_default_content_settings.images": 2,
            "profile.default_content_setting_values.notifications": 2
        }
        options.add_experimental_option("prefs", prefs)
        
        # 指定ChromeDriver路径
        service = Service('/usr/bin/chromedriver')
        driver = webdriver.Chrome(service=service, options=options)
        
        # 执行反检测脚本
        driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
        
        return driver
    
    def should_use_proxy(self) -> bool:
        """判断是否需要使用代理"""
        # 当请求次数过多时建议使用代理
        return self.request_count > 100
    
    def get_proxy_list(self) -> List[str]:
        """获取代理列表（示例，实际使用时需要配置真实代理）"""
        # 这里应该配置真实的代理服务器
        return [
            # "http://proxy1:port",
            # "http://proxy2:port",
        ]
    
    def reset_counter(self) -> None:
        """重置请求计数器"""
        self.request_count = 0
        self.last_request_time = 0